import pigRepurchasesApi from '../../../common/api/cbs/pigrepurchases.api.js';
import doT from '../../../../vendor/template/doT.js';
import { uploadFile, requestFilePath, publicFileDraw, sliceFileName } from '../../../common/api/file-request.js';
import { Select2Info, Select2Page } from '../../../common/serve-request.js';
import { locationService } from '../../../common/locationService.js';
import { DictionaryType, requestDict } from '../../../common/dictionary/dictionary-type.js';

let _vm;
const addsaleTemplate = doT.template($('#addsaleorders-template').text());
const curOrg = JSON.parse(Utils.GetSessionStorage('SNLoginUserInfo'));
let pigRequrchaseLevel, specLeveltype;
(function (window, document, $) {
    $(function () {
        _vm = new Vue({
            el: '#addsaleorders-form',
            data() {
                return {
                    breedBatch: {
                        id: '',
                        name: '',
                    },
                    fiOrg: {
                        id: '',
                        name: '',
                    },
                    depOrg: {
                        id: '',
                        name: '',
                    },
                    fosterFarmer: {
                        id: '',
                        name: '',
                    },
                    bizDate: moment(new Date()).format('YYYY-MM-DD'),
                    remark: '',
                    entries: [],
                    uploadCount: 0,
                    attaches: [],
                    isHerdingPig: false,
                    totalCount: '',
                    totalWeight: '',
                    totalAmount: '',
                    curQty: '',
                };
            },
            mounted() {
                let url = location.href;
                let params = {}; // url参数
                for (let key of new URL(url).searchParams.entries()) {
                    key[1] ? (params[key[0]] = key[1]) : '';
                }
                let ids = Utils.GetSessionStorage('ids');
                if (params.id || ids) {
                    document.title = '猪只回购单 - 编辑';
                }
            },
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
        clickFun();
        _initCommand();
        uploadInit();
    });
    // 附件上传
    const uploadInit = () => {
        weui.uploader('#uploader', {
            url: '',
            auto: false,
            type: 'file',
            compress: { isNoTCompress: true },
            onBeforeQueued: function (files) {
                if (!isMobile() && files.length > 0) {
                    $.toptip('请使用手机拍照上传！', 'warning');
                    return false;
                }
                if (['image/jpg', 'image/jpeg', 'image/png'].indexOf(this.type) < 0) {
                    $.toptip('请上传图片', 'warning');
                    return false; // 阻止文件添加
                }
                $.showLoading('上传中..');
                _vm.uploadCount = ++_vm.uploadCount;
                if (_vm.uploadCount == 3) {
                    $('.weui-uploader__input-box').hide();
                }
            },
            onQueued: async function () {
                const file = this;
                let suffix = this.name.split('.').pop().toLowerCase(); //截取附件后缀
                let name = this.name.slice(0, 11 - suffix.length - 1); //计算截取文件的11位字符
                let newName = name + '.' + suffix;
                let file1 = publicFileDraw(newName, _vm);
                // 在这里添加日期和地点水印
                const currentDate = moment(new Date()).format('YYYY-MM-DD');
                const currentTime = moment(new Date()).format('HH:mm:ss');
                const locationWatermark = $('#addressInfo').text();
                const canvas = document.createElement('canvas');
                const context = canvas.getContext('2d');
                const image = new Image();
                image.src = window.URL.createObjectURL(file);

                if (!Utils.IsNotNull(locationWatermark)) {
                    $.toptip('定位失败!', 'warning');
                    $.hideLoading();
                    $('#uploaderFiles').last().empty();
                    return;
                }
                image.onload = function () {
                    canvas.width = image.width;
                    canvas.height = image.height;
                    // 在canvas上绘制原始图片
                    context.drawImage(image, 0, 0);

                    // 添加水印，支持换行
                    const watermarkText = currentDate + ' ' + currentTime + '\n' + locationWatermark;
                    context.font = '700 ' + 80 + 'px Arial';
                    context.fillStyle = 'white';

                    // 在指定位置绘制文本
                    const x = 10;
                    const y = image.height - 160;
                    drawWrappedText(context, watermarkText, x, y, 200, 130); // 调用自定义函数

                    // 将canvas转为Blob
                    canvas.toBlob(function (blob) {
                        const formData = new FormData();
                        formData.append('apiobjfile', blob, file1);
                        _uploadFileDraw(formData, file, _vm);
                    }, file.type || 'image/png'); // 使用原始图片的类型或默认为PNG
                };
            },
        });
        $('#uploaderFiles').click(function (e) {
            let target = e.target;
            while (!target.classList.contains('weui-uploader__file') && target) {
                target = target.parentNode;
            }
            if (!target) return;
            //从图片对应的li标签中获得所需属性
            let gallery = weui.gallery($(target).attr('data-url'), {
                className: 'custom-name',
                onDelete: function () {
                    //删除图片的回调
                    $.confirm({
                        title: '删除提示',
                        text: '确定删除该图片？',
                        onOK: function () {
                            let _id = $(target).attr('data-id');
                            _vm.attaches = _vm.attaches.filter((item) => item.id != _id);
                            _vm.uploadCount = --_vm.uploadCount;
                            target.remove();
                            gallery.hide();
                            // 添加3张后隐藏上传按钮
                            if (_vm.uploadCount == 3) {
                                $('.weui-uploader__input-box').hide();
                            } else {
                                $('.weui-uploader__input-box').show();
                            }
                        },
                        onCancel: function () {},
                    });
                },
            });
        });
    };
    // 自定义函数，用于在Canvas上绘制换行的文本
    function drawWrappedText(context, text, x, y, maxWidth, lineHeight) {
        var words = text.split('\n');
        var line = '';
        var yOffset = 0;

        for (var i = 0; i < words.length; i++) {
            var word = words[i];
            var testLine = line + word + ' ';
            var metrics = context.measureText(testLine);
            var testWidth = metrics.width;

            if (testWidth > maxWidth && i > 0) {
                context.fillText(line, x, y + yOffset);
                line = word + ' ';
                yOffset += lineHeight;
            } else {
                line = testLine;
            }
        }

        context.fillText(line, x, y + yOffset);
    }
    function isMobile() {
        return /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
    }

    // 附件上传
    const _uploadFileDraw = (formFile, upFiles, _vm, newName) => {
        uploadFile(formFile)
            .then(async (res) => {
                if (res.isSucceed) {
                    let imageurl = await requestFilePath(res.data);
                    let _list = _vm.attaches;
                    _list.push({
                        id: $('#uploaderFiles li').length,
                        imageId: res.data,
                        url: imageurl.data,
                    });
                    _vm.attaches = _list;
                    $('#uploaderFiles li').each(function (i) {
                        $(this).attr('data-id', _vm.attaches[i].id);
                        $(this).attr('data-image-id', _vm.attaches[i].imageId);
                        $(this).attr('data-url', _vm.attaches[i].url);
                        $(this).css({ 'background-image': `url(${_vm.attaches[i].url})` });
                    });
                    $('.weui-uploader__file-content').hide();
                    $('.weui-uploader__file').removeClass('weui-uploader__file_status');
                }
            })
            .catch((res) => {
                $('#uploaderFiles li')
                    .eq($('#uploaderFiles li').length - 1)
                    .remove();
                _vm.uploadCount = --_vm.uploadCount;
                $.toptip(res.msg, 'error');
            })
            .finally((_) => {
                $.hideLoading();
                $.closeModal();
            });
    };
    // 编辑回显
    const _images = async (file) => {
        let _imag = file;
        if (_imag) {
            let _sun = 0;
            for (let i = 0; i < _imag.length; i++) {
                ++_sun;
                await requestFilePath(_imag[i].imageId).then((_res) => {
                    _vm.attaches.push({
                        id: _sun,
                        url: _res.data,
                        imageId: _imag[i].imageId,
                    });
                    if (_res.isSucceed) {
                        let _li;
                        _li = `<li class="weui-uploader__file" data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i].imageId}" style="background-image: url(${_res.data}) "></li>`;
                        $('#uploaderFiles').append(_li);
                    }
                });
            }
            if (_sun == 3) {
                $('.weui-uploader__input-box').hide();
            }
            _vm.uploadCount = _sun;
        }
    };

    // 初始化数据
    const _initCommand = async () => {
        pigRequrchaseLevel = await requestDict(DictionaryType.PIGREQURCHASELEVEL_TYPE);
        specLeveltype = await requestDict(DictionaryType.SPECLEVEL_TYPE);
        // 选择日期
        $('#search-date').on('click', function () {
            pick();
        });
        // //获取养殖批次
        // Select2Info($(`#breedBatch`), `${Utils.CurDomain.BaseCfgUrl}/breedbatchs/cur`, (params) => {
        //     return JSON.stringify({
        //         searchInfo: params.term,
        //         tags: ""
        //     })
        // }, "POST", {
        //     allowClear: true,//允许清空
        //     placeholder: '请选择养殖批次...', //默认文字提示
        //     templateResult: function (res) {
        //         return `${res.name}`;
        //     }
        // });
        // $('#breedBatch').setSelectValue();

        //养户信息
        Select2Page(
            $(`#fosterFarmer`),
            `${Utils.CurDomain.CBSUrl}/fosterfarmers/by/q`,
            (params) => {
                return {
                    OrgId: curOrg.coui,
                    SearchInfo: params.term,
                    pageSize: 10,
                    pageIndex: (params.page || 1) - 1,
                };
            },
            'GET',
            {
                allowClear: true, //允许清空
                placeholder: '请选择养户...', //默认文字提示
                templateResult: function (res) {
                    return `${res.name}(${res.phone})`;
                },
            },
        );

        // 初始化养殖批次
        $('#breedBatch').empty().select2({
            placeholder: '请选择养殖批次...', //默认文字提示
            language: 'zh-CN', //汉化
            allowClear: true, //允许清空
        });
        $('#fosterFarmer').on('select2:select', async function () {
            let _batch = await pigRepurchasesApi.getFosterfarmers($(this).val());
            $('#breedBatch')
                .empty()
                .select2({
                    placeholder: '请选择养殖批次...', //默认文字提示
                    language: 'zh-CN', //汉化
                    allowClear: true, //允许清空
                    data: _batch.map((item) => {
                        return {
                            id: item.breedBatchId,
                            text: item.breedBatchName,
                        };
                    }),
                });
            $('#breedBatch').setSelectValue();
            _vm.fosterFarmer.id = $('#fosterFarmer').select2('data')[0]?.id;
            _vm.fosterFarmer.name = $('#fosterFarmer').select2('data')[0]?.name;
        });

        // 选择批次
        $('#breedBatch').on('select2:select', async function () {
            //查询存栏数
            let quantity = await pigRepurchasesApi.postBreedbatchsNum({ id: $(this).val(), bizDate: _vm.bizDate });
            _vm.curQty = quantity?.totalNum;
            let breedBatchInfo = $('#breedBatch').select2('data')[0];
            // 获取 其他信息
            let otherInfo = await pigRepurchasesApi.getbreedbatch({ searchInfo: breedBatchInfo.text });
            _vm.breedBatch.id = otherInfo[0]?.id;
            _vm.breedBatch.name = otherInfo[0]?.name;
            _vm.fiOrg.id = otherInfo[0]?.fiOrgId;
            _vm.fiOrg.name = otherInfo[0]?.fiOrgName;
            _vm.depOrg.id = otherInfo[0]?.farmOrgId;
            _vm.depOrg.name = otherInfo[0]?.farmOrgName;
            // let fstfarm = breedBatchInfo.name.split('-')
            // console.log(fstfarm)
            // let fosterfarmers = await pigRepurchasesApi.getfosterfarmers(fstfarm[1])
            // console.log(fosterfarmers?.items[0])
            // _vm.fosterFarmer = fosterfarmers?.items[0]
        });

        // 编辑
        let ids = getUrlKey('id');
        if (Utils.IsNotNull(ids)) {
            $('#informationSubmit').text('保存');
            await pigRepurchasesApi.getPigRepurchases(ids).then(async (res) => {
                Utils.SetRouterState('deliverDatas', res);
                JSON.stringify(Utils.SetSessionStorage('ids', ids));
                res.entries.forEach((item, index) => (item.id = index));
                JSON.stringify(Utils.SetSessionStorage('getEntryInfo', res.entries));
                let quantity = await pigRepurchasesApi.postBreedbatchsNum({ id: res.breedBatch.id, bizDate: _vm.bizDate });
                _vm.curQty = quantity?.totalNum;
            });
        }

        // 获取主表数据
        let getMainInfo = JSON.parse(Utils.GetSessionStorage('deliverDatas'));
        if (Utils.IsNotNull(getMainInfo)) {
            $('#fosterFarmer').setSelectValue(getMainInfo.fosterFarmer.id, getMainInfo.fosterFarmer.name);
            $('#breedBatch').setSelectValue(getMainInfo.breedBatch.id, getMainInfo.breedBatch.name);
            _vm.breedBatch = getMainInfo.breedBatch;
            _vm.fiOrg = getMainInfo.fiOrg;
            _vm.depOrg = getMainInfo.depOrg;
            _vm.bizDate = getMainInfo.bizDate || moment(getMainInfo.bizFormObj?.bizDate).format('YYYY-MM-DD');
            _vm.remark = getMainInfo.remark;
            _vm.fosterFarmer = getMainInfo.fosterFarmer;
            _vm.isHerdingPig = getMainInfo.isHerdingPig;
            _vm.totalCount = getMainInfo.totalCount;
            _vm.totalWeight = getMainInfo.totalWeight;
            _vm.totalAmount = getMainInfo.totalAmount;
            _vm.curQty = _vm.curQty || getMainInfo.curQty;
            let editImage = [];
            if (Utils.IsNotNull(getMainInfo.attaches) && !Utils.IsNotNull(ids)) {
                _images(getMainInfo.attaches);
                _vm.uploadCount = getMainInfo.uploadCount;
            } else if (Utils.IsNotNull(getMainInfo.attaches)) {
                getMainInfo.attaches.split(',').forEach((item) => {
                    editImage.push({
                        imageId: item,
                    });
                });
                _images(editImage);
                _vm.uploadCount = getMainInfo.attaches.split(',').length;
            }
        }

        // 获取分录信息
        let getEntryInfo = JSON.parse(Utils.GetSessionStorage('getEntryInfo'));
        // 渲染 分录
        if (Utils.IsNotNull(getEntryInfo)) {
            let newInfo = [...getEntryInfo];
            newInfo.forEach((item) => {
                item.priceUnit = item.isSettlementQty == true ? '元/头' : '元/kg';
                item.requrchaseLevelName = pigRequrchaseLevel.data.find((itm) => itm.value == item.requrchaseLevel)?.displayName;
                item.specLevelName = specLeveltype.data.find((itm) => itm.value == item.specLevel)?.displayName;
            });
            $('#salesEntry').empty().append(addsaleTemplate(newInfo));
            let totalCount = 0,
                totalWeight = 0,
                totalAmount = 0;
            getEntryInfo.map((item) => {
                totalCount += Number(item.count);
                totalWeight += Number(item.weight);
                totalAmount += Number(item.amount);
            });
            _vm.totalCount = totalCount;
            _vm.totalWeight = totalWeight;
            _vm.totalAmount = totalAmount;
        }
    };

    const pick = () => {
        weui.datePicker({
            defaultValue: moment(new Date()).format('YYYY-MM-DD').split('-'),
            end: moment(new Date()).format('YYYY-MM-DD'),
            className: 'mypick',
            onConfirm: async function (result) {
                let value = `${result[0].value}-${result[1].value}-${result[2].value}`;
                // _vm.bizDate = moment(new Date(value)).format('YYYY-MM-DD')
                _vm.bizDate = result.map((item) => item.value).join('-');
                if (Utils.IsNotNull(_vm.breedBatch.id)) {
                    //查询存栏数
                    let quantity = await pigRepurchasesApi.postBreedbatchsNum({ id: _vm.breedBatch.id, bizDate: _vm.bizDate });
                    _vm.curQty = quantity?.totalNum;
                }
            },
        }); // 默认配置
    };

    // 保存分录以上的内容
    const storeSession = () => {
        let _mainInfo = {
            ...{ breedBatch: _vm.breedBatch },
            ...{ fiOrg: _vm.fiOrg },
            ...{ depOrg: _vm.depOrg },
            ...{ fosterFarmer: _vm.fosterFarmer },
            bizDate: _vm.bizDate,
            remark: _vm.remark,
            attaches: _vm.attaches,
            uploadCount: _vm.uploadCount,
            curQty: _vm.curQty,
            isHerdingPig: _vm.isHerdingPig,
            totalCount: _vm.totalCount,
            totalWeight: _vm.totalWeight,
            totalAmount: _vm.totalAmount,
        };
        let deliverDatas = { ..._mainInfo };
        // 保存数据内容
        Utils.SetRouterState('deliverDatas', deliverDatas);
    };

    // 操作函数
    const clickFun = () => {
        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            // 删除分录 删除页面数据 删除ID
            window.sessionStorage.removeItem('getEntryInfo');
            window.sessionStorage.removeItem('deliverDatas');
            window.sessionStorage.removeItem('ids');
            location.href = `../pigrepurchases/pigrepurchaseslist.html?v=${Utils.GetTime()}`;
        });

        //取消，关闭弹框
        $(document).on('click', '#returnAddSaleOrders', function () {
            $('#pop').css('display', 'none');
            $('.show-box').css('display', 'none');
            $('.show-box').css({
                bottom: '-6rem',
                transition: 'all .ls ease-in',
            });
        });

        // 点击分录
        $('#add-saleEntry').on('click', function (e) {
            // 存储数据
            storeSession();
            // 获取分录 否则 默认是0
            let index = JSON.parse(Utils.GetSessionStorage('getEntryInfo'))?.length || 0;
            location.href = `../pigrepurchases/pigrepurchasesentry.html?v=${Utils.GetTime()}&index=${index}&isEdit=${false}`;
        });

        // 提交数据
        $('#informationSubmit').on('click', function (e) {
            let entries = JSON.parse(Utils.GetSessionStorage('getEntryInfo'));
            if (!Utils.IsNotNull(_vm.fosterFarmer.id)) {
                return $.toptip(`请选择养户!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.breedBatch.id)) {
                return $.toptip(`请选择养殖批次!`, 'warning');
            }
            // if (Number(_vm.curQty) < Number(_vm.totalCount)) {
            //     return $.toptip("回购总数量不能大于存栏数量", 'warning');

            // }
            if (!Utils.IsNotNull(entries)) {
                return $.toptip(`请添加猪只回购单分录信息!`, 'warning');
            }

            savetips();
        });

        // 删除分录
        $(document).on('click', '#salesEntry div[data-flag=table-click-delete]', function () {
            let id = $(this).data('index');
            $.modal({
                autoClose: false,
                title: '删除提示',
                text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
					<div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
						<div>是否确认删除该分录?</div>
					</div>`,
                buttons: [
                    {
                        text: '取消',
                        className: 'default',
                        onClick: function () {
                            $.closeModal();
                        },
                    },
                    {
                        text: '确定',
                        onClick: function () {
                            let getEntryInfo = JSON.parse(Utils.GetSessionStorage('getEntryInfo'));
                            // 将删除数据删除
                            let datas = getEntryInfo.filter((item) => item.id != id);
                            // 重置id
                            let info =
                                datas.map((item, index) => {
                                    item.id = index;
                                    return item;
                                }) || [];
                            // 处理数据
                            let newInfo = [...info];
                            newInfo.forEach((item) => {
                                item.requrchaseLevelName = pigRequrchaseLevel.data.find((itm) => itm.value == item.requrchaseLevel)?.displayName;
                                item.specLevelName = specLeveltype.data.find((itm) => itm.value == item.specLevel)?.displayName;
                            });

                            // 重新计算
                            let totalCount = 0,
                                totalWeight = 0,
                                totalAmount = 0;
                            info.map((item) => {
                                totalCount += Number(item.count);
                                totalWeight += Number(item.weight);
                                totalAmount += Number(item.amount);
                            });
                            _vm.totalCount = totalCount;
                            _vm.totalWeight = totalWeight;
                            _vm.totalAmount = totalAmount;

                            // 渲染数据
                            $('#salesEntry').empty().append(addsaleTemplate(newInfo));
                            // 存分录
                            JSON.stringify(Utils.SetSessionStorage('getEntryInfo', info));

                            $.closeModal();
                        },
                    },
                ],
            });
        });

        // 编辑 分录
        $(document).on('click', '#salesEntry div[data-flag=table-click-edit]', function () {
            // 存储数据
            storeSession();
            // 获取分录 否则 默认是0
            let index = $(this).data('index');
            location.href = `../pigrepurchases/pigrepurchasesentry.html?v=${Utils.GetTime()}&index=${index}&isEdit=${true}`;
        });
    };
    // 保存
    const savetips = () => {
        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style = "margin-top:-5px" >
                    <div class="addedientry" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
                        <div class="addentry" >是否确认保存该单据？</div>
                    </div> 
                    </div>`,
            buttons: [
                {
                    text: '取消',
                    className: 'default',
                    onClick: function () {
                        $.closeModal();
                    },
                },
                {
                    text: '保存',
                    onClick: function () {
                        $.closeModal();
                        let ids = Utils.GetSessionStorage('ids');
                        let entries = JSON.parse(Utils.GetSessionStorage('getEntryInfo'));

                        let imageArr = [];
                        _vm.attaches.forEach((item) => {
                            imageArr.push(item.imageId);
                        });
                        let attachesStr = imageArr.join(',');

                        let datas = {
                            ...{ breedBatch: _vm.breedBatch },
                            ...{ fiOrg: _vm.fiOrg },
                            ...{ depOrg: _vm.depOrg },
                            ...{ fosterFarmer: _vm.fosterFarmer },
                            bizDate: _vm.bizDate,
                            remark: _vm.remark,
                            attaches: attachesStr,
                            uploadCount: _vm.uploadCount,
                            curQty: _vm.curQty,
                            isHerdingPig: _vm.isHerdingPig,
                            totalCount: _vm.totalCount,
                            totalWeight: _vm.totalWeight,
                            totalAmount: _vm.totalAmount,
                            entries: [...entries],
                        };
                        if (Utils.IsNotNull(ids)) {
                            return pigRepurchasesApi.putPigRepurchases(ids, JSON.stringify(datas)).then((res) => {
                                $.toptip('请求成功。', 'success');
                                // 延时一秒跳转  要看提示
                                setTimeout(function () {
                                    window.sessionStorage.removeItem('getEntryInfo');
                                    window.sessionStorage.removeItem('deliverDatas');
                                    window.sessionStorage.removeItem('ids');
                                    location.href = `../pigrepurchases/pigrepurchaseslist.html?v=${Utils.GetTime()} `;
                                }, 1000);
                            });
                        } else {
                            pigRepurchasesApi.postPigRepurchases(JSON.stringify(datas)).then(
                                (res) => {
                                    $.toptip('请求成功。', 'success');
                                    // 延时一秒跳转  要看提示
                                    setTimeout(function () {
                                        window.sessionStorage.removeItem('getEntryInfo');
                                        window.sessionStorage.removeItem('deliverDatas');
                                        location.href = `../pigrepurchases/pigrepurchaseslist.html?v=${Utils.GetTime()} `;
                                    }, 1000);
                                },
                                (err) => {
                                    $.toptip(err.responseJSON?.msg, 'error');
                                },
                            );
                        }
                    },
                },
            ],
        });
    };

    // 获取地址栏的 参数
    const getUrlKey = (name) => {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    };
    //解决字段过长问题
    const cutstr = (str, len) => {
        var str_length = 0;
        var str_len = 0;
        var str_cut = new String();
        str_len = str.length;
        for (var i = 0; i < str_len; i++) {
            var a = str.charAt(i);
            str_length++;
            if (escape(a).length > 4) {
                //中文字符的长度经编码之后大于4
                str_length++;
            }
            str_cut = str_cut.concat(a);
            if (str_length >= len) {
                str_cut = str_cut.concat('...');
                return str_cut;
            }
        }
        //如果给定字符串小于指定长度，则返回源字符串；
        if (str_length < len) {
            return str;
        }
    };
})(window, document, jQuery);
